#include "include/tools/stock_table_delegate.hpp"
#include <QApplication>
#include <QPainter>

StockTableDelegate::StockTableDelegate(QObject *parent)
    : QStyledItemDelegate(parent) {}

void StockTableDelegate::paint(QPainter *painter,
                               const QStyleOptionViewItem &option,
                               const QModelIndex &index) const {
  QStyleOptionViewItem opt = option;
  initStyleOption(&opt, index);

  // 设置涨跌颜色
  if (index.column() == 2 ||
      index.column() == 3) { // 假设第3列是价格，第4列是涨跌幅
    double value = index.data().toDouble();
    if (index.column() == 3) { // 涨跌幅列
      if (value > 0) {
        opt.palette.setColor(QPalette::Text, Qt::red);
      } else if (value < 0) {
        opt.palette.setColor(QPalette::Text, Qt::green);
      }
    }
  }

  // 调用默认绘制
  QStyledItemDelegate::paint(painter, opt, index);
}

QString StockTableDelegate::displayText(const QVariant &value,
                                        const QLocale &locale) const {
  // 格式化数字显示
  if (value.type() == QVariant::Double) {
    double val = value.toDouble();

    // 价格显示两位小数
    return QString::number(val, 'f', 2);
  }

  return QStyledItemDelegate::displayText(value, locale);
}
